package com.qinxueit.admin.task;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.qinxueit.admin.api.ParseHtml;
import com.qinxueit.admin.entity.Article;
import com.qinxueit.admin.entity.Chapter;
import com.qinxueit.admin.service.ArticleService;
import com.qinxueit.admin.service.ChapterService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

@Component
public class TaskParseHtml {

    @Autowired
    private ArticleService articleService;
    @Autowired
    private ChapterService chapterService;

    /**
     * 每隔20秒执行一次
     * 根据小说表的url，爬取具体的章节
     */
    @Scheduled(cron = "0/20 * * * * ?")
    public void chapterTask() throws Exception {
        List<Article> articleList = articleService.list(new QueryWrapper<Article>().select("article_id", "url_status"));
        for (Article article : articleList) {
            List<Chapter> chapterLists = chapterService.list(new QueryWrapper<Chapter>().isNotNull("source_url").eq("url_status",article.getUrlStatus()));
            //System.out.println(articleLists);
            ArrayList<Chapter> chapterArrayList = new ArrayList<>();
            for (Chapter chapter : chapterLists) {
                Chapter newChapter = ParseHtml.getChapterList(chapter);
                if (newChapter != null){
                    chapterArrayList.add(newChapter);
                }

                Thread.sleep(2000);
            }

            if(!chapterArrayList.isEmpty()){
                System.out.println(chapterArrayList);
                boolean b = chapterService.saveBatch(chapterArrayList);
                if (b == true){
                    article.setBookStatus(1);
                    articleService.save(article);
                }

            }
        }
    }
}
